package com.vision.world.survey.activities;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.SystemClock;
import android.speech.RecognizerIntent;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.quinny898.library.persistentsearch.SearchBox;
import com.quinny898.library.persistentsearch.SearchResult;
import com.vision.world.survey.Interface.OnTouchMapEvent;
import com.vision.world.survey.Interface.view.IMainView;
import com.vision.world.survey.R;
import com.vision.world.survey.fragments.BoundaryFragment;
import com.vision.world.survey.fragments.IndentifyResultFragment;
import com.vision.world.survey.fragments.SearchFragment;
import com.vision.world.survey.fragments.SettingLayerFragment;
import com.vision.world.survey.managers.AuthorizationManager;
import com.vision.world.survey.managers.LayerManager;
import com.vision.world.survey.managers.MapManager;
import com.vision.world.survey.managers.QueryManager;
import com.vision.world.survey.presenter.MainPresenter;
import com.vision.world.survey.util.CommonUtil;
import com.vision.world.survey.util.MapTools;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,
        SettingLayerFragment.OnSettingLayerFragmentListener, IMainView, LocationListener {
    private MapView mMapView;
    private SearchBox search;
    private ListView lvSearchResult = null;
    private LinearLayout llShowDetail = null;
    //    private LinearLayout llBoundaryResult=null;
    private LinearLayout llSearchPanel = null;
    private RelativeLayout rlSearchView = null;
    private RelativeLayout rlSettingLayer = null;
    //    private ImageButton imgbtnSearchBox=null;
    private ImageButton imgbtnChangelayer = null;
    private ImageButton imgbtnPosition = null;//位置居中
    private ImageButton imgbtnSelectBoundary = null;
    private ImageButton imgbtnZoomOut = null;
    private ImageButton imgbtnZoomIn = null;
    private SettingLayerFragment mSettingLayerFragment = null;
    private BoundaryFragment mBoundaryFragment = null;
    private IndentifyResultFragment mIndentifyResultFragment = null;
    private SearchFragment mSearchFragment = null;


    private TextView txtSearchKey;
    private TextView txtSearchName;
    private LayerManager mLayerManager = null;
    private ProgressBar progressBar = null;
    private MainPresenter mMainPresenter = null;

    //退出时的时间
    private long mExitTime;

    public MainActivity() {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_layout);
        ////////////////////
        //FIXME 虚拟位置设定
//        initL();
        //加载在线地图
        mMapView = (MapView) findViewById(R.id.mapView);
        mMapView.setAttributionTextVisible(false);
//        //本地坐标：116.393646,39.989825
        //ArcGISMap map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, 39.989825, 116.393646, 16);
//        mMapView.setMap(map);


        initData();
        initView();
        initFragment();
        AuthorizationManager.initAuthorizationMap();
        initMap();
        initSearch();
        initIndentify();


    }

    public void initIndentify() {
        //设置地图identify事件
        QueryManager.getInstance().initIdentifyOperation(this, mMapView, new OnTouchMapEvent() {
            @Override
            public void refreshViewOnStartSearch(String info) {
            }

            @Override
            public void refreshViewOnStartSearch(MotionEvent e) {
                llShowDetail.setVisibility(View.GONE);
                CommonUtil.screenNo = 0;
                //显示查询滚动条
                CommonUtil.showProgressDialog(MainActivity.this, getResources().getString(R.string.search_by_screenlocation));
            }

            @Override
            public void refreshViewOnSearchSuccess(String info, int count) {

                if (count > 0) {
                    mMapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayShowResult).getGraphics().clear();
                    llShowDetail.setVisibility(View.VISIBLE);
                    Map<String, Object> result = QueryManager.getInstance().SearchResultFromOperationLayer.get(0);
                    mIndentifyResultFragment.setsResult(result);
                    getFragmentManager().beginTransaction().replace(R.id.ll_show_detail_panel, mIndentifyResultFragment).commit();
//                    mIndentifyResultFragment.setResultInfo(result);
                    /**Set<String> resultk = result.keySet();
                     int i=0;
                     for (String key : resultk) {
                     if(!key.equals("FID")&& !key.equals("GOE") && !key.equals("LAYERNAME") && !key.equals("OBJECTID") && !key.equals("Shape") ){
                     txtList.get(i).setText(key+"：");
                     i++;
                     txtList.get(i).setText(result.get(key).toString());
                     i++;
                     Log.i("Identify",key+"："+result.get(key).toString());
                     }
                     }*/
                }
                CommonUtil.showMessage(MainActivity.this, info);
                //Log.i("Identify","查询成功，查到结果数量："+count+"条");
                CommonUtil.dismissProgressDialog();
            }

            @Override
            public void refreshViewOnSearchFailed(String info, Exception ex) {
                llShowDetail.setVisibility(View.GONE);
                CommonUtil.showMessage(MainActivity.this, info + ":\n" + ex.getMessage());
                Log.w("Identify", ex.getMessage());
                //关闭查询进度条
                CommonUtil.dismissProgressDialog();
            }
        });

    }

    public void initData() {
        mMainPresenter = new MainPresenter(this, this);
    }

    String searchitem = null;

    public void initSearch() {
        //search
        search = (SearchBox) findViewById(R.id.searchbox);
        search.enableVoiceRecognition(this);
        /** for (int x = 0; x < 10; x++) {
         SearchResult option = new SearchResult("Result " + Integer.toString(x), getResources().getDrawable(R.drawable.ic_clear));
         search.addSearchable(option);
         }*/
        search.setLogoText("查找");
        search.setLogoTextColor(Color.rgb(136, 136, 136));
        /**search.setMenuListener(new SearchBox.MenuListener() {
        @Override public void onMenuClick() {
        //Hamburger has been clicked
        //                Toast.makeText(MainActivity.this, "Menu click", Toast.LENGTH_LONG).show();
        }

        });*/

        search.setSearchListener(new SearchBox.SearchListener() {

            @Override
            public void onSearchOpened() {
                //Use this to tint the screen
                Log.i("search", "open");
            }

            @Override
            public void onSearchClosed() {
                //Use this to un-tint the screen
//                Log.i("search", "close");
            }

            @Override
            public void onSearchTermChanged(String s) {
                searchitem = s;
//                Log.i("search", "onSearchTermChanged"+searchitem);
            }

            @Override
            public void onSearch(String searchTerm) {
                searchitem = searchTerm;
//                Log.i("search","onSearch"+searchitem);

                //searchTermToast.makeText(MainActivity.this, searchTerm + " Searched", Toast.LENGTH_LONG).show();
                mMainPresenter.search(searchTerm, mMapView);
            }

            @Override
            public void onResultClick(SearchResult result) {
                Log.i("search", "onResultClick");
                //React to a result being clicked
            }


            @Override
            public void onSearchCleared() {
                Log.i("search", "onResultClick");
            }
        });
        search.setOverflowMenu(R.menu.overflow);
        search.setOverflowMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.test_menu_item:
                        Log.i("search", "searchitem=" + searchitem);
                        mMainPresenter.search(searchitem, mMapView);
//                        Toast.makeText(MainActivity.this, "Clicked!", Toast.LENGTH_SHORT).show();
                        return true;
                }
                return false;
            }
        });
    }

    public void initMap() {
        mMainPresenter.initMap(this, mMapView, progressBar);
//        mLayerManager=LayerManager.getInstance();
//        mLayerManager.iniBaseMap(this,mMapView);
//        mLayerManager.initGraphicOverlay(mMapView);
//        mLayerManager.initLayerOperatinal(this,mMapView);
//        //设置地图显示范围
//        mLayerManager.changeViewPoint(mMapView);
        //地图刷新进度条
//        MapTools.initDrawStatusChanged(this,mMapView,progressBar);
    }

    public void initView() {
        imgbtnChangelayer = (ImageButton) findViewById(R.id.imgbtn_change_layer);
        imgbtnChangelayer.setOnClickListener(this);
        rlSettingLayer = (RelativeLayout) findViewById(R.id.rl_layer_setting);
        rlSettingLayer.setVisibility(View.GONE);
        rlSearchView = (RelativeLayout) findViewById(R.id.search_view1);
        rlSearchView.setOnClickListener(this);
        llSearchPanel = (LinearLayout) findViewById(R.id.ll_search_panel);
        llSearchPanel.setVisibility(View.GONE);
//        imgbtnSearchBox=(ImageButton) findViewById(R.id.imgbtn_search_box);
//        imgbtnSearchBox.setOnClickListener(this);
        imgbtnPosition = (ImageButton) findViewById(R.id.img_btn_position_center);
        imgbtnPosition.setOnClickListener(this);
        imgbtnSelectBoundary = (ImageButton) findViewById(R.id.imgbtn_map_select);
        imgbtnSelectBoundary.setOnClickListener(this);
        imgbtnZoomOut = (ImageButton) findViewById(R.id.img_btn_zoom_out);
        imgbtnZoomOut.setOnClickListener(this);
        imgbtnZoomIn = (ImageButton) findViewById(R.id.img_btn_zoom_in);
        imgbtnZoomIn.setOnClickListener(this);
        //地图刷新时的进度条
        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        //查询结果显示
        llShowDetail = (LinearLayout) findViewById(R.id.ll_show_detail_panel);
        llShowDetail.setVisibility(View.GONE);
//        llBoundaryResult=(LinearLayout)findViewById(R.id.ll_fragment_boundary_result);
//        llBoundaryResult.setVisibility(View.VISIBLE);


        txtSearchKey = (TextView) findViewById(R.id.txt_show_search_key);
        txtSearchName = (TextView) findViewById(R.id.txt_show_search_count);

        //搜索框结果显示
        lvSearchResult = (ListView) findViewById(R.id.lv_search_result);
        lvSearchResult.setAdapter(mMainPresenter.getSearchResultAdapter());
        lvSearchResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Map<String, Object> result = QueryManager.getInstance().SearchResultFromOperationLayer.get(i);
                llShowDetail.setVisibility(View.VISIBLE);

                getFragmentManager().beginTransaction().replace(R.id.ll_show_detail_panel, mSearchFragment).commit();
                mSearchFragment.setsResult(result);

                /*String strGeo = (String)result.get(Util.KEY_GEOJSON);
                Geometry geo = Geometry.fromJson(strGeo);*/
                Geometry geo = (Geometry) result.get(CommonUtil.KEY_GEO);
                Envelope envelope = geo.getExtent();

                final ListenableFuture<Boolean> viewpointSetFuture = mMapView.setViewpointAsync(new Viewpoint(envelope), 2);

                //设置小水滴显示
                mMapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayPoint).getGraphics().clear();
                Graphic graphic = new Graphic(geo, CommonUtil.getSymbolDefaultPictureMapker(mMapView.getContext()));
                mMapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayPoint).getGraphics().add(graphic);
                llSearchPanel.setVisibility(View.GONE);
            }
        });

    }

    public void initFragment() {
        //layer设置fragment初始化
        mSettingLayerFragment = new SettingLayerFragment(this);
        mSettingLayerFragment.setListener(this);
        getFragmentManager().beginTransaction().replace(R.id.rl_layer_setting, mSettingLayerFragment).commit();
        mBoundaryFragment = new BoundaryFragment(this, mMapView);
        mIndentifyResultFragment = new IndentifyResultFragment(this);
        getFragmentManager().beginTransaction().replace(R.id.ll_show_detail_panel, mIndentifyResultFragment).commit();
        mSearchFragment = new SearchFragment(this);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == 4 && event.getRepeatCount() == 0) {
            if (event.getAction() == event.ACTION_DOWN) {

                int a = llSearchPanel.getVisibility();
                if (a == View.VISIBLE) {
                    llSearchPanel.setVisibility(View.GONE);
                } else {
                    exit();
                }
                return true;
            } else {
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i("退出", "onKeyDown" + event.getRepeatCount());
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Log.i("退出", "onKeyDown caozuoli" + event.getRepeatCount());
            llSearchPanel.setVisibility(View.GONE);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1234 && resultCode == RESULT_OK) {
            ArrayList<String> matches = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            search.populateEditText(matches.get(0));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onPause() {
        mMapView.pause(); //
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.resume();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imgbtn_change_layer:
                llShowDetail.setVisibility(View.GONE);
                rlSettingLayer.setVisibility(View.VISIBLE);
                break;
            case R.id.search_view1:
                llShowDetail.setVisibility(View.GONE);
                llSearchPanel.setVisibility(View.VISIBLE);
                llShowDetail.setVisibility(View.GONE);
                txtSearchKey.setText("");
                txtSearchName.setText("");
                List<Map<String, Object>> items = new ArrayList<>();
                mMainPresenter.getSearchResultAdapter().setItem(items);
                mMainPresenter.getSearchResultAdapter().notifyDataSetChanged();
                search.setFocusable(true);
                break;
            case R.id.img_btn_position_center:
                MapManager.positionCenter(mMapView);
                break;
            case R.id.imgbtn_map_select:
                llShowDetail.setVisibility(View.GONE);
                mMainPresenter.selectByLocationBoundary(mMapView);
                break;
            case R.id.img_btn_zoom_out:
                double i = mMapView.getMapScale();
                i = i / 2;
                mMapView.setViewpointScaleAsync(i);
                Log.i("zoom ", "scale  =" + i);
                break;
            case R.id.img_btn_zoom_in:
                double scale = mMapView.getMapScale();
                scale = scale * 2;
                mMapView.setViewpointScaleAsync(scale);
                break;
            default:
                break;
        }
    }

    @Override
    public void OnDismissPanel() {
        rlSettingLayer.setVisibility(View.GONE);
    }

    @Override
    public void OnChangeLayer(String url) {
        //todo mLayerManager 干啥用的，View层不要出现数据的好
        // mLayerManager.switchBaseMap(mMapView,url);
        LayerManager.getInstance().switchBaseMap(mMapView, url);
    }

    @Override
    public void showSearchViewResult(String queryKey, String info, int count) {
        txtSearchKey.setText(queryKey);
        info = info.substring(info.indexOf("：") + 1, info.length());
        txtSearchName.setText(info);
    }

    @Override
    public void shouBoundaryResult() {
//        mBoundaryFragment=new BoundaryFragment(this);
        List<Map<String, Object>> SearchResult = QueryManager.getInstance().SearchResultFromOperationLayer;
        Log.i("boundary1", "结果：" + SearchResult.size());
        if (SearchResult.size() > 0) {
            getFragmentManager().beginTransaction().replace(R.id.ll_show_detail_panel, mBoundaryFragment).commit();
            if (mBoundaryFragment.adapter != null) {
                mBoundaryFragment.adapter.setItem(QueryManager.getInstance().SearchResultFromOperationLayer);
                mBoundaryFragment.adapter.notifyDataSetChanged();
            }
            llShowDetail.setVisibility(View.VISIBLE);
        } else {
            llShowDetail.setVisibility(View.GONE);
        }
    }


    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            // 
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    private String mMockProviderName = LocationManager.GPS_PROVIDER;
    ;
    private LocationManager locationManager;
    private double latitude = 19.4279645947, longitude = 109.9484379274;// 默认海南
    private Thread thread;// 需要一个线程一直刷新
    private Boolean is_run = true;

    private void init_location() {
        locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);
        locationManager.addTestProvider(mMockProviderName, false, true, false, false, true, true, true, 0, 5);
        locationManager.setTestProviderEnabled(mMockProviderName, true);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            Log.e("ddd","权限不对");
            return;
        }
        locationManager.requestLocationUpdates(mMockProviderName, 0, 0, this);
    }

    @SuppressLint("NewApi")
    private void setLocation(double longitude, double latitude) {
        Location location = new Location(mMockProviderName);
        location.setTime(System.currentTimeMillis());
        location.setLatitude(latitude);
        location.setLongitude(longitude);
        location.setAltitude(2.0f);
        location.setAccuracy(3.0f);
        location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
        locationManager.setTestProviderLocation(mMockProviderName, location);
    }

    public void initL(){
        init_location();
        thread = new Thread(new Runnable() {

            @Override
            public void run() {
                while (is_run) {
                    try {
                        Thread.sleep(10000);
                        setLocation(longitude, latitude);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
        thread.start();
    }


    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
}
